package com.yungu.swift.api.route.v1.driver;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.JsonNode;
import com.yungu.swift.api.base.BaseApi;
import com.yungu.swift.api.utils.RandomUtil;
import com.yungu.swift.assets.driver.model.dto.DriverDto;
import com.yungu.swift.assets.driver.model.dto.DriverLogDto;
import com.yungu.swift.assets.driver.model.vo.DriverVo;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.utils.HttpUtils;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.StringUtils;
import com.yungu.swift.utils.ValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.yungu.swift.api.config.NacosListener.WXPAY_CONFIG;

/**
 * Description:DriLoginApi 司机登陆接口
 * Author: Zerrion
 * Date:2016/12/9 17:31
 */
@Controller
@RequestMapping(value = "/api/v1/driver")
@Api(value = "【司机】【登录】司机登陆接口", tags = "司机登陆相关操作")
public class DriLoginApi extends BaseApi {

    @Reference
    private DriverService driverService;

    @ApiOperation(value = "司机登陆接口", notes = "返回成功或失败消息")
    @RequestMapping(value = "/login/login", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResponseData<DriverVo> Drilogin(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "type", value = "司机类型（1.出租车，2专车 3跨城拼车）") @RequestParam(value = "type", required = false) Integer type,
            @ApiParam(name = "mobile", value = "手机号", required = true) @RequestParam String mobile,
            @ApiParam(name = "password", value = "密码", required = true) @RequestParam String password,
            @ApiParam(name = "deviceType", value = "操作系统（1：android，2：IOS）") @RequestParam(value = "deviceType", required = false) Integer deviceType,
            @ApiParam(name = "deviceToken", value = "设备唯一标示") @RequestParam(value = "deviceToken", required = false) String deviceToken,
            @ApiParam(name = "deviceVersion", value = "操作系统版本号") @RequestParam(value = "deviceVersion", required = false) String deviceVersion,
            @ApiParam(name = "appVersion", value = "应用版本") @RequestParam(value = "appVersion", required = false) String appVersion,
            @ApiParam(name = "lng", value = "当前用户所在位置的经度") @RequestParam(value = "lng", required = false) Double lng,
            @ApiParam(name = "lat", value = "当前用户所在位置的纬度") @RequestParam(value = "lat", required = false) Double lat,
            @ApiParam(name = "mac", value = "用户端mac地址") @RequestParam(value = "mac", required = false) String mac,
            @ApiParam(name = "imei", value = "用户端IMEI") @RequestParam(value = "imei", required = false) String imei,
            @ApiParam(name = "hardSign", value = "硬件特征串") @RequestParam(value = "hardSign", required = false) String hardSign,
            HttpServletRequest request) {

        String decryptMobile = RandomUtil.randomDecrypt(mobile);
        if (!ValidateUtils.validateMobile(decryptMobile)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "请输入正确的手机号");
        }
        String decryptPassword = RandomUtil.randomDecrypt(password);
        if (StringUtils.isEmpty(decryptPassword)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "密码错误");
        }
        //司机信息
        DriverDto driver = new DriverDto();
        driver.setMobile(decryptMobile);
        driver.setPassword(decryptPassword);
        driver.setDeviceType(deviceType);
        driver.setDeviceToken(deviceToken);
        driver.setDeviceVersion(deviceVersion);
        driver.setAppVersion(appVersion);
        driver.setAppid(appid);
        driver.setBusinessType(type);
        // 设置为激活状态
        driver.setActive(1);
        //司机log信息
        DriverLogDto driverLogDto = new DriverLogDto();
        driverLogDto.setIp(getUserIP(request));
        driverLogDto.setPort(request.getRemotePort());
        driverLogDto.setLat(lat);
        driverLogDto.setLng(lng);
        driverLogDto.setMac(mac);
        driverLogDto.setImei(imei);
        driverLogDto.setHardwareSignature(hardSign);
        return driverService.login(driver, driverLogDto);
    }

    @ApiOperation(value = "司机登出接口", notes = "返回成功或失败消息", response = ResponseData.class)
    @RequestMapping(value = {"/token/login/logout"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public ResponseData<Boolean> driverLoginout(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "token", value = "用户token", required = true) @RequestParam String token,
            @ApiParam(name = "offWorkLng", value = "收车经度", required = false) @RequestParam(required = false) Double offWorkLng,
            @ApiParam(name = "offWorkLat", value = "收车纬度", required = false) @RequestParam(required = false) Double offWorkLat,
            @ApiParam(name = "uploadText", value = "长连接上传的报文", required = false) @RequestParam(required = false) String uploadText) {

        return driverService.logout(token, appid, offWorkLng, offWorkLat, uploadText);
    }

    @ApiOperation(value = "司机微信授权")
    @PostMapping(value = {"/token/wx/access"})
    @ResponseBody
    public ResponseData<Map<String, String>> wxAccess(
            @ApiParam(name = "code", value = "code", required = true) @RequestParam String code, HttpServletRequest request) throws IOException {
        String driverWxAppid = WXPAY_CONFIG.getDriverWxAppid();
        String driverWxAppSecret = WXPAY_CONFIG.getDriverWxAppSecret();
        // 1. 授权登陆
        String authUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                driverWxAppid, driverWxAppSecret, code);
        String authorization = HttpUtils.getResponseString(authUrl);
        if (StringUtils.isEmpty(authorization)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "微信方授权异常，请稍后再试");
        }
        JsonNode authNode = JsonUtils.readNode(authorization);
        if (authNode.get("errcode") != null) {
            return ResponseData.buildErrorResponse(authNode.get("errcode").asInt(0), authNode.get("errmsg").toString());
        }
        String openid = authNode.get("openid").asText();
        DriverDto driverDto = new DriverDto();
        driverDto.setUuid(getUserUid(request));
        driverDto.setOpenId(openid);
        driverService.edit(driverDto);
        Map<String, String> result = new HashMap<>(2);
        result.put("openId", openid);
        return ResponseData.buildSuccessResponse("微信授权成功", result);
    }

}
